<template>
  <!--
  此组件说明：
* 1. 当前选择图片change时：组件向父级通信，参数为此图片的base64
  2. 点击清除：点击后清除当前所选择的文件，组件向父级通信，参数为""
  3. 传入参数：直接是base64字符串或者url，用于文件框内的显示来源
  -->
  <div>
    <el-upload
      class="avatar-uploader"
      :action="configdata.uploadUrl"
      :show-file-list="false"
      :on-change="getFile"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
      :limit="1"
      :auto-upload="true"
      list-type="picture"
    >
      <img v-if="imgBase64" :src="imgBase64" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-button size="mini" type="text" class="clearbtn" @click="handleClear">点击清除</el-button>
    <div class="tip_div" v-if="configdata.tiplist && configdata.tiplist.length > 0">
      <template v-for="(item,index) in configdata.tiplist">
        <p :key="index">
          <span>*</span>
          {{item}}
        </p>
      </template>
    </div>
    <publicComponent
      :msgConfig="publicComponentObj.msgConfig"
      :confirmConfig="publicComponentObj.confirmConfig"
    ></publicComponent>
  </div>
</template>
<script>
import { read } from 'fs'
export default {
  name: 'tplUpload',
  props: ['fdata'],
  data () {
    return {
      publicComponentObj: {
        confirmConfig: {},
        msgConfig: {}
      },
      imgBase64: '',
      configdata: {
        uploadUrl: '',
        tiplist: [],
        imageType: 'image/png',
        imageUrl: '',
        imageTypeTip: '上传头像图片只能是 PNG 格式!',
        imageSize: '',
        imageSizeTip: '上传头像图片大小不能超过 2MB!'
      }
    }
  },
  created () {
    // this.configdata = this.fdata;
    this.imgBase64 = this.fdata // 图片的base64地址
  },
  methods: {
    // 清除当前选择的图片文件
    handleClear () {
      this.imgBase64 = ''
      this.$emit('sonToFather', { imgBase64: this.imgBase64 })
    },
    httpRequest () {
      console.log('http-request')
    },
    getBase64 (file) {
      // 把图片转成base64编码
      return new Promise(function (resolve, reject) {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    getFile (file, fileList) {
      console.log('on-change')
      // this.imgBase64 = "";
      // 上传头像
      this.getBase64(file.raw).then(res => {
        this.imgBase64 = res
        this.$emit('sonToFather', { imgBase64: this.imgBase64 })
      })
    },
    // 文件上传成功时的钩子
    handleAvatarSuccess (res, file) {
      console.log('on-success')
      this.configdata.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传文件之前的钩子
    beforeAvatarUpload (file) {
      return false // 这里只能返回false 才会每次触发on-change
      // 如果返回true  只会触发一次on-change和http-request
      // 参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
      const isJPG = file.type === this.configdata.imageType
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        var tempMsgObj = {
          message: this.configdata.imageTypeTip,
          type: 'error',
          showClose: true,
          duration: 3000
        }
        this.publicComponentObj.msgConfig = tempMsgObj
      }
      if (!isLt2M) {
        var tempMsgObj = {
          message: this.configdata.imageSizeTip,
          type: 'error',
          showClose: true,
          duration: 3000
        }
        this.publicComponentObj.msgConfig = tempMsgObj
      }
      return isJPG && isLt2M
    },
    previewBanner (file) {
      // 看了一下源码，file 里有个属性 raw , 其实就是rawFile
      let reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        let _base64 = reader.result
        doWhatUWant(_base64) // 就可以做你想做的啦！！！
      }
    }
  }
}
</script>
<style scoped>
.tip_div > p {
  margin-left: 0px;
  line-height: 24px;
  margin-top: 10px;
  color: #9fa9b9;
  font-size: 12px;
}
.tip_div > p > span {
  color: red;
  margin-right: 6px;
}
</style>
<style>
.avatar-uploader {
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.clearbtn {
  width: 178px;
  text-align: right;
  text-decoration: underline;
}
</style>


